package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.to.MemberVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //TODO 通过openFeign发的请求没带cookie，先放行
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        if(antPathMatcher.match("/order/order/**",request.getRequestURI())
        && !antPathMatcher.match("/order/order/listWithItem",request.getRequestURI())){
            return true;
        }

        if (antPathMatcher.match("/payed/notify",request.getRequestURI())){
            return true;
        }

        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthConstant.LOGIN_USER);
        if(attribute != null){
            loginUser.set((MemberVo) attribute);
            return true;
        }else{
            session.setAttribute("errorMessage","请先登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
